<?php
    class App
    {
        public $renderer;
        
        public $start_time;
        public $controller;
        public $controller_obj;
        public $action;
        public $parameters = array();
        
        public function __construct()
        {
            $this->start_time = microtime(true);
            $full_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $url = explode(CONF_BASE,$full_url);
            $url_part = array();
            
            if(count($url) === 2)
            {
                $url_part = explode("/", $url[1]);
            }
            
            if (count($url_part) >= 2)
            {
                $this->controller = array_shift($url_part);
                $this->action = array_shift($url_part);
                $this->parameters = $url_part;
            }
            else if (count($url_part) >= 1)
            {
                $this->controller = array_shift($url_part);
                $this->action = CONF_DEFAULT_ACTION;
                $this->parameters = array();
            }
            
            if(!file_exists(CONF_CONTROLLER.$this->controller.'.php'))
            {
                 $this->controller = CONF_DEFAULT_CONTROLLER;
                 $this->action = CONF_DEFAULT_ACTION;
                 $this->parameters = array();
            }
            
            include_once CONF_CONTROLLER.$this->controller.'.php';
            if (!class_exists($this->controller))
            {
                $this->controller = CONF_DEFAULT_CONTROLLER;
                $this->action = CONF_DEFAULT_ACTION;
                $this->parameters = array();
                
                include_once CONF_CONTROLLER.$this->controller.'.php';
            }
            
            if (!method_exists($this->controller, $this->action))
            {
                $this->controller = CONF_DEFAULT_CONTROLLER;
                $this->action = CONF_DEFAULT_ACTION;
                $this->parameters = array();
                
                include_once CONF_CONTROLLER.$this->controller.'.php';
            }

            $this->renderer = new Renderer();
        }
        
        public function getNavigation()
        {
            return array($this->controller, $this->action);
        }
        
        public function dispatch()
        {
            $this->controller_obj = new $this->controller($this);   
            
            $start_time = $this->start_time;
            $navigation = $this->getNavigation();
            $renderer = $this->renderer;
            $content = call_user_func_array(array($this->controller_obj, $this->action), $this->parameters);
            
             if(DEBUG)
                 var_dump($this);
            
            include_once CONF_VIEW.'layout.php';
        }
    }

?>